'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: 3_with_file_memory_study.py
* @Time: 2025/10/24
* @All Rights Reserve By Brtc
'''
from multiprocessing.connection import answer_challenge
from typing import Any

import dotenv
from langchain_community.chat_message_histories import FileChatMessageHistory
from openai import OpenAI
dotenv.load_dotenv()
client = OpenAI(base_url="https://api.ephone.chat/v1")

# 1、增加一个file 内存记忆类
chat_history = FileChatMessageHistory("./mem.txt")

if __name__ == "__main__":
    #定义一个对话缓冲窗口记忆类(参数是 摘要 + 历史记录 + tokens数量)

    while True:
        human_input = input("你好我是博小睿客服助手,请输入您的问题>")# 人类输入的问题
        if human_input == "exit":
            print("goodbye!!")
            exit(0)
        #2、添加到提示中
        system_prompt = (
            "你是一个强大的聊天机器人，请根据用户上下文来回答问题。\n\n"
            f"<context>{chat_history}</context>\n" # 历史记录添加到 提示词中
        )
        completion = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role":"system", "content":system_prompt},
                {"role":"user", "content":human_input},
            ],
            stream = True
        )
        print("博小睿:", end = "", flush=True)
        ai_content = ""
        for chunk in completion:
            content = chunk.choices[0].delta.content

            if content  is None:
                break
            ai_content += content
            print(content, end = "", flush=True)
        # 增加消息AI消息 +  人类消息
        chat_history.add_user_message(human_input)
        chat_history.add_ai_message(ai_content)# 存储
        print("\n---------------------------------------------\n")

